<template>
  <div class="trend-wrapper">
    <div class="trend-header">
      <div class="title">{{ $t('workplace.trend.title') }}</div>
      <a-radio-group v-model="timeUnit" type="button" @change="handleTimeChange">
        <a-radio value="day">{{ $t('workplace.trend.day') }}</a-radio>
        <a-radio value="month">{{ $t('workplace.trend.month') }}</a-radio>
        <a-radio value="year">{{ $t('workplace.trend.year') }}</a-radio>
      </a-radio-group>
    </div>
    <div ref="chartRef" class="chart-container" :loading="loading"></div>
  </div>
</template>

<script lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useI18n } from 'vue-i18n';
import * as echarts from 'echarts';
import { getReceiveLineChart } from '@/api/dashboard';

export default {
  name: 'DataTrend',
};
</script>

<script lang="ts" setup>


const { t } = useI18n();
const chartRef = ref();
const loading = ref(false);
const timeUnit = ref('day');
let chart: echarts.ECharts | null = null;

const handleTimeChange = () => {
  fetchData();
};

const fetchData = async () => {
  try {
    loading.value = true;
    const response = await getReceiveLineChart({
      unit: timeUnit.value
    });
    const chartData = response.data || [];
    console.log('API Response:', response);
    
    if (chartData.length === 0) {
      updateChart([], []);
      return;
    }

    const xAxisData = chartData.map(item => item.date);
    const seriesData = chartData.map(item => {
      const value = typeof item.value === 'string' ? parseFloat(item.value) : item.value;
      return Number(value) || 0;
    });

    console.log('Processed Data:', { xAxisData, seriesData });
    updateChart(xAxisData, seriesData);
  } catch (error) {
    console.error('获取折线图数据失败:', error);
    updateChart([], []);
  } finally {
    loading.value = false;
  }
};

const updateChart = (xAxisData: string[], seriesData: number[]) => {
  if (!chartRef.value) return;

  if (chart) {
    chart.dispose();
  }
  
  chart = echarts.init(chartRef.value);

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const [param] = params;
        return `${param.name}<br/>${t('workplace.trend.income')}: ¥${param.value.toFixed(2)}`;
      }
    },
    grid: {
      top: 10,
      left: '3%',
      right: '4%',
      bottom: '12%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLabel: {
        interval: 2,
        formatter: (value: string) => value.replace(':00', '')
      },
      axisLine: {
        lineStyle: {
          color: '#E5E6EB'
        }
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      splitNumber: 4,
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#E5E6EB',
          type: 'dashed'
        }
      },
      axisLabel: {
        formatter: (value: number) => `¥${value.toFixed(2)}`,
        margin: 16,
      }
    },
    series: [{
      name: t('workplace.trend.income'),
      type: 'line',
      smooth: true,
      data: seriesData,
      symbolSize: 6,
      showSymbol: false,
      emphasis: {
        focus: 'series',
        showSymbol: true
      },
      itemStyle: {
        color: '#165DFF'
      },
      lineStyle: {
        width: 2,
        color: '#165DFF'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(22, 93, 255, 0.2)'
          },
          {
            offset: 1,
            color: 'rgba(22, 93, 255, 0)'
          }
        ])
      }
    }]
  };

  chart.setOption(option);
};

onMounted(() => {
  fetchData();
  window.addEventListener('resize', () => {
    if (chart) {
      chart.resize();
    }
  });
});

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose();
    chart = null;
  }
});
</script>

<style scoped lang="less">
.trend-wrapper {
  .trend-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0 24px;

    .title {
      font-size: 14px;
      font-weight: 500;
    }
  }
  
  .chart-container {
    height: 140px;
  }
}
</style> 